package su.msk.jet.team01.chatik.common;

import java.util.HashMap;
import java.util.Map;

public final class ArgsExtractor {
	private final Map<String, String> args = new HashMap<String, String>();
	private String currentArg = "";
	
	public ArgsExtractor() {
		
	}
	
	public ArgsExtractor(final String str) {
		extract(str);
	}
	
	public ArgsExtractor(final String[] strs) {
		extract(strs);
	}
	
	public void extract(final String str) {
		extract(str.split(" "));
	}
	
	public void extract(final String[] strs) {
		for (String str : strs) {
			parseWord(str);
		}
		if(!currentArg.isEmpty()) {
			addParameterWithoutValue();
		}
	}

	public String getArg(final String arg) {
		final String strArgs = args.get(arg);
		if (strArgs != null) {
			return strArgs;
		}
		return "";
	}

	public String getArg(final String arg, final String defaultValue) {
		String value = getArg(arg);
		return (value.isEmpty() ? defaultValue : value);
	}

	public Map<String, String> getArgs() {
		return args;
	}

	private void addParameterWithoutValue() {
		args.put(currentArg, "true");
	}

	private void addParameterWithValue(final String str) {
		if (!currentArg.equals("")) {
			args.put(currentArg, str);
			currentArg = "";
		}
	}

	private boolean isParameterKey(final String str) {
		return str.startsWith("-");
	}

	private void parseWord(final String str) {
		if (isParameterKey(str)) {
			if (!currentArg.equals("")) {
				addParameterWithoutValue();
			}
			currentArg = str.substring(1, str.length());
		} else {
			addParameterWithValue(str);
		}
	}
}
